package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.service.SetmealDishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增菜品
     *
     * @return
     */
    public void saveDish(DishVO dishVO) {

        //将DishVO属性拷贝到Dish
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishVO, dish);
        dishMapper.insertDish(dish);
        Long dishId = dish.getId();


        //获取口味数据
        List<DishFlavor> flavors = dishVO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(flavor -> {
                flavor.setDishId(dishId);
            });
            dishFlavorMapper.insertDishFlavor(flavors);
        }
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    public PageResult DishPageQuery(DishPageQueryDTO dishPageQueryDTO) {

        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        Page<Dish> page = dishMapper.pageQuery(dishPageQueryDTO);
        long total = page.getTotal();
        List<Dish> records = page.getResult();

        return new PageResult(total, records);
    }

    /**
     * 根据ID返回菜品数据
     *
     * @param id
     * @return
     */
    public DishVO queryDishById(Long id) {
        //获取基础信息
        Dish dish = dishMapper.selectDishById(id);
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectDishFlavorByDishId(id);

        //将基础信息拷贝到dishvo中
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    /**
     * 修改菜品
     *
     * @param dishVO
     */
    public void updateDish(DishVO dishVO) {
        //将dishVO数据拷贝到dish中
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishVO, dish);

        //修改dish表中的数据
        dishMapper.updateDish(dish);

        //修改dishFlavors -1.删除表中数据，2.添加新的数据
        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishVO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            //1.删除表中数据
            dishFlavorMapper.deleteDishFlavorByDishIds(new Long[]{dishId});
            //2.添加新的数据
            flavors.forEach(flavor -> {
                flavor.setDishId(dishId);
            });
            dishFlavorMapper.insertDishFlavor(flavors);
        }
    }


    /**
     * 根据ids批量删除菜品
     *
     * @param ids
     */
    @Transactional//增加事务，保证数据一致性
    public void deleteDishByIds(Long[] ids) {
        //判断菜品状态是否为启用，如果为启动，提示删除失败
        Integer count = dishMapper.selectDishCountByIds(ids);
        log.info("根据ids查询满足条件的菜品数目:{}", count);
        if (count != 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }

        //判断菜品是都与套餐关联，如果关联，返回失败信息
        List<Long> setmealIds = setmealDishService.getSetmealDishIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ENABLE_FAILED);
        }

        //都没有以上条件，删除dish
        dishMapper.deleteDishByIds(ids);

        //删除关联的口味信息
        dishFlavorMapper.deleteDishFlavorByDishIds(ids);
    }

    /**
     * 根据id修改状态
     *
     * @param status
     * @param id
     */
    public void starAndStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.updateDish(dish);

    }

    /**
     * 条件查询菜品和口味
     *
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {

        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();

        List<Dish> list = dishMapper.list(dish);

        return list;

    }


}
